package sellControllers

import (
	"WEB/models"
	"github.com/astaxie/beego/orm"
	"github.com/astaxie/beego/validation"
	"strings"
)

type SellGoodController struct {
	SellBaseController
}

func GetAllSellGoodByStore(storeId int, onlySell bool) []models.Goods {
	newOrm := orm.NewOrm()
	var goods []models.Goods
	var sql string
	if onlySell == true {
		sql = models.QueryByEqualField(models.Goods{}, "GoodStoreId", "GoodIsSell")
		_, e := newOrm.Raw(sql, storeId, 1).QueryRows(&goods)
		if e != nil {
			panic(e)
		}
	} else {
		sql = models.QueryByEqualField(models.Goods{}, "GoodStoreId")
		_, e := newOrm.Raw(sql, storeId).QueryRows(&goods)
		if e != nil {
			panic(e)
		}
	}
	for i, v := range goods {
		goods[i].GoodStoreName = models.GetStoreByPrimarkKey(v.GoodStoreId).StoresName
	}
	return goods
}

// @router /sell/addGood [get]
func (this *SellGoodController) GetGoodManagePage() {
	this.TplName = "sell/goodManager.html"
}

// @router /sell/goodManage [post]
func (this *SellGoodController) PostGoodManage() {

	// check form
	var temp models.Goods
	if err := this.ParseForm(&temp); err != nil {
		this.Redirect("/error?info="+err.Error(), 302)
		return
	}

	valid := validation.Validation{}
	valid.Required(temp.GoodName, "goodName")
	valid.Required(temp.GoodDescription, "goodInfo")
	valid.Required(temp.GoodStorage, "goodStorage")
	valid.Required(temp.GoodPrices, "goodPrices")
	valid.Required(temp.GoodKindId, "goodKindId")

	errors := valid.HasErrors()
	if errors {
		msg := make([]string, 0)
		for _, v := range valid.Errors {
			msg = append(msg, v.Error())
		}
		this.Redirect("/error?info="+strings.Join(msg, ""), 302)
		return
	}

	//name cant be same
	newOrm := orm.NewOrm()

	var good models.Goods
	sql := models.QueryByEqualField(good, "GoodName")
	row := newOrm.Raw(sql, temp.GoodName).QueryRow(&good)
	if row == nil {
		this.Redirect("/error?info=GoodExsit", 302)
		return
	}
	file, header, row := this.GetFile("file")
	if row != nil {
		this.Redirect("/erroe?info="+row.Error(), 302)
	}
	defer file.Close()

	path := "static/upload/good/" + header.Filename

	this.SaveToFile("file", path)

	store := this.GetSession("store").(models.Stores)

	temp.GoodStoreId = store.StoresId
	temp.GoodUrl = header.Filename

	sql = models.InsertWithoutPrimaryKey(temp)

	_, row = newOrm.Raw(sql, models.GetFieldValue(temp, models.IsPrimaryKey)).Exec()

	if row != nil {
		this.Redirect("/error?info="+row.Error(), 302)
	}

	this.Redirect("/sell/index", 302)

}

// @router /sell/good
func (this *SellGoodController) GetGoodDetail() {
	goodId, e := this.GetInt("id")
	if e != nil {
		panic(e)
	}
	orm := orm.NewOrm()
	var good models.Goods
	sql := models.QueryByPrimaryKey(good)
	e = orm.Raw(sql, goodId).QueryRow(&good)
	if e != nil {
		this.Redirect("error?info="+e.Error(), 302)
		return
	}
	this.Data["Good"] = good
	this.TplName = "sell/details.html"
}

// @router /sell/goodManage [get]
func (this *SellGoodController) GoodList() {
	this.TplName = "sell/goodManage.html"
}

// @router /sell/getGoodList [get]
func (this *SellGoodController) GetGoodList() {
	store := this.GetSession("store").(models.Stores)
	goods := GetAllSellGoodByStore(store.StoresId, false)
	this.Data["json"] = map[string]interface{}{
		"code": 0,
		"msg":  "ok",
		"data": goods,
	}
	this.ServeJSON()
}

// @router /sell/setGoodSell [post]
func (this *SellGoodController) SetGoodSell() {
	goodId, err := this.GetInt("goodId")
	if err != nil {
		this.Data["json"] = map[string]interface{}{
			"code": 1,
			"msg":  "ok",
		}
		this.ServeJSON()
		return
	}
	value := this.GetString("value")
	if value == "" {
		panic(err)
	}
	var realValue int
	var msg string
	if value == "true" {
		realValue = 1
		msg = "上架成功"
	} else {
		realValue = 0
		msg = "下架成功"
	}
	var good models.Goods
	good = models.SelectAllFromGoodWherePrimaryKey(goodId)
	good.GoodIsSell = realValue
	sql := models.UpdateFieldsByPrimary(good, "GoodIsSell")
	_, err = orm.NewOrm().Raw(sql, good.GoodIsSell, goodId).Exec()
	if err != nil {
		panic(err)
	}

	this.Data["json"] = map[string]interface{}{
		"code": 0,
		"msg":  msg,
	}
	this.ServeJSON()
}

// @router /sell/deleteGood [post]
func (this *SellGoodController) DelGood() {
	goodId, err := this.GetInt("goodId")
	if err != nil {
		panic(err)
	}
	var good models.Goods
	sql := models.DeleteByField(good, "GoodId")
	_, err = orm.NewOrm().Raw(sql, goodId).Exec()
	if err != nil {
		panic(err)
	}
	this.Data["json"] = map[string]interface{}{
		"code": 0,
		"msg":  "ok",
	}
	this.ServeJSON()
}

// @router /sell/editGood [post]
func (this *SellGoodController) EditGood() {
	goodId, err := this.GetInt("goodId")
	if err != nil {
		panic(err)
	}
	field := this.GetString("field")
	if field == "" {
		this.Data["json"] = map[string]interface{}{
			"code": 1,
			"msg":  "ok",
		}
		this.ServeJSON()
		return
	} else {
		var good models.Goods
		good = models.SelectAllFromGoodWherePrimaryKey(goodId)

		switch field {

		case "GoodPrices":
			value, err := this.GetFloat("value")
			if err != nil {
				panic(err)
			}
			sql := models.UpdateFieldsByPrimary(good, "GoodPrices")
			_, err = orm.NewOrm().Raw(sql, value, goodId).Exec()
		case "GoodStorage":
			value, err := this.GetInt("value")
			if err != nil {
				panic(err)
			}
			sql := models.UpdateFieldsByPrimary(good, "GoodStorage")
			_, err = orm.NewOrm().Raw(sql, value, goodId).Exec()
		case "GoodRefPrices":
			value, err := this.GetFloat("value")
			if err != nil {
				panic(err)
			}
			sql := models.UpdateFieldsByPrimary(good, "GoodRefPrices")
			_, err = orm.NewOrm().Raw(sql, value, goodId).Exec()
		case "GoodName":
			value := this.GetString("value")
			sql := models.UpdateFieldsByPrimary(good, "GoodName")
			_, err = orm.NewOrm().Raw(sql, value, goodId).Exec()
		case "GoodUrl":
			value := this.GetString("value")
			sql := models.UpdateFieldsByPrimary(good, "GoodUrl")
			_, err = orm.NewOrm().Raw(sql, value, goodId).Exec()
		}

		if err != nil {
			panic(err)
		}
		this.Data["json"] = map[string]interface{}{
			"code": 0,
			"msg":  "ok",
		}
		this.ServeJSON()
	}

}
